<template>
    <div>
        <Row :gutter="20" class="margin-bottom-20">
            <i-col span="8">
                <DatePicker
                    :clearable="false"
                    v-model="search.date"
                    type="daterange"
                    placeholder="选择创建时间"
                    style="width:100%"
                />
            </i-col>
            <i-col span="8">
                <i-input placeholder="姓名/手机号码" v-model="search.keyword"></i-input>
            </i-col>
            <i-button @click="handleSearch">搜索</i-button>
        </Row>

        <Table :data="tableData" :columns="columns" :loading="loading"></Table>

        <div class="text-center margin-top-20">
            <Page
                show-total
                :current.sync="pagination.current"
                :total="pagination.total"
                :page-size="pagination.limit"
                @on-change="handlePageChange"
            />
        </div>
    </div>
</template>

<script>
    import debouce from 'lodash/debounce'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { searchTimeRange, now, quarterAgo, date } from '@/libs/date'

export default {
      name: 'm3-open-history',
      props: {
        deviceInfo: Object,
        roomId: Number
      },
      data () {
        return {
          loading: false,
          pagination: {
            current: 1,
            total: 0,
            limit: 20
          },
          search: {
            date: [ quarterAgo, now ],
            keyword: ''
          },
          tableData: [],
          columns: [
            { title: '授权ID', render: (h, { row }) => <span>{row.auth_id ? row.auth_id : '-'}</span> },
            { title: '开门人', key: 'user' },
            { title: '开门时间', key: 'openTime' }
          ],
          roleMap: {
            1: '员工',
            2: '租客'
          }
        }
      },
      created () {
        this.initData(true)
      },
      methods: {
        getQuery () {
          const { current, limit } = this.pagination
          const { date, keyword } = this.search
          const [ start_time, end_time ] = searchTimeRange(date)
          const query = util.cleanObj({
            limit,
            start_time,
            end_time,
            offset: (current - 1) * limit
          }, [0])

          if (keyword) {
            if (/^\d+$/.test(keyword)) {
              query.phone = keyword
            } else {
              query.name = keyword
            }
          }
          return query
        },
        handleSearch: debouce(function () {
          this.pagination.current = 1
          this.initData(true)
        }, 200),
        handlePageChange () {
          this.initData(false)
        },
        async initData (recount = false) {
          try {
            this.loading = true
            const { roomId, deviceInfo: { id } } = this
            const ids = [ roomId, id ]
            const query = this.getQuery()
            if (recount) this.fetchCount(ids, query)
            const res = await http.req(api.m3_open_records, ids, query)
            if (res) {
              res.rows.forEach(item => {
                item.user = `[${this.roleMap[item.relation_role] || ''}]${item.relation_name}`
                item.openTime = date(item.open_time, 'YYYY-MM-DD HH:mm')
              })
              this.tableData = res.rows
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        async fetchCount (ids, query) {
          try {
            const res = await http.req(api.m3_open_records_count, ids, query)
            if (res) this.pagination.total = res.count
          } catch (err) {
            console.log(err)
          }
        }
      }
    }
</script>